package com.itcam.sort.mergesort;

import java.util.Arrays;

/**
 * @author : Cammy.Wu
 * Description : 归并排序(自上而下)
 */

public class SplitSortTopDown {
    public static void main(String[] args) {
        int[] a = {9, 5, 7, 12, 1, 3};
        System.out.println(Arrays.toString(a));
        mergeSort(a);
        System.out.println(Arrays.toString(a));
    }

    // 方法2——非递归
    public static void merge(int[] a1, int i, int iEnd, int j, int jEnd, int[] a2) {
        int k = i;
        while (i <= iEnd && j <= jEnd) {
            if (a1[i] < a1[j]) {
                a2[k] = a1[i];
                i++;
            } else {
                a2[k] = a1[j];
                j++;
            }
            k++;
        }
        if (i > iEnd) {
            System.arraycopy(a1, j, a2, k, jEnd - j + 1);
        }
        if (j > jEnd) {
            System.arraycopy(a1, i, a2, k, iEnd - i + 1);
        }
    }


    private static void mergeSort(int[] a) {
        int[] newa = new int[a.length];
        split(a, 0, a.length - 1, newa);
    }

    private static void split(int[] a, int left, int right, int[] newa) {
        int[] array = Arrays.copyOfRange(a, left, right + 1);
//        System.out.println(Arrays.toString(array));
        // 2.治
        if (left == right) {
            return;
        }
        // 1.分
        int mid = (left + right) >>> 1;
        split(a, left, mid, newa);
        split(a, mid + 1, right, newa);
        // 3.合
        merge(a, left, mid, mid + 1, right, newa);
        System.arraycopy(newa, left, a, left, right - left + 1);
    }
}
